import React, { Component } from 'react';
import { CloseOutlined,ExclamationCircleOutlined } from '@ant-design/icons';
import { Button, Modal, message } from 'antd';
import { _getAddrList, _delAddrList, _editAddrList,_addAddrList,_createDefault } from "../Api/api";

import "./index.css";

const { confirm } = Modal;


export default class Home extends Component {
    state = {
        list: [],
        username: "",
        city: "",
        address: "",
        mobile: "",
        tell: '',
        email: "",
        id: 0,
        is_default: 0,
        visible: false,
        flag: false

    }
// 初始化调用
    componentDidMount() {
        this.getInitList();
    }
    // 获取初始数据
    async getInitList() {
        let { data } = await _getAddrList();
        console.log(data);
        this.setState({
            list: data.result
        })
    }

    // 新增地址
    createAddress = () => {
    
        this.setState({flag:true})
    }
// 保存收货地址
    keepawaryAddr = async() =>{
        let { username, city, address, mobile, tell, email} = this.state;
        let obj = { username, city, address, mobile, tell, email};
        // console.log(obj);
        const {data} = await _addAddrList(obj);
        console.log(data)
        if(data.code===1){
            message.success(data.msg);
             this.setState({flag:false});
             this.getInitList();
        }else{
            message.success(data.msg);
            this.setState({flag:false});
            this.getInitList();
        }
       
    }

    // handlerAdd  新增的受控组件
    handlerAdd = (e) => {
        this.setState({
            [e.target.name]: e.target.value
        })
       
    }

    // 删除
    showDeleteConfirm(id) {
        var that = this;
        confirm({
          title: '确定要删除吗?',
          icon: <ExclamationCircleOutlined />,
          
          okText: '确定',
          okType: 'danger',
          cancelText: '取消',
         async onOk() {
           
            
            let { data } = await _delAddrList(id);
          
            if (data.code === 1) {
                // 删除成功后进行全局提示 再调用获取列表
                message.success(data.msg).then(setTimeout(() => {
                   
                    that.getInitList();
                   
                }, 3000));
            }
          },
          onCancel() {
            console.log('取消删除');
          },
        });
      }

    //   设为默认地址
      editDefault = async(id)=>{
          console.log(id,'设为默认地址');
          const res = await _createDefault({id});
          console.log(res);
          if(res.data.code===1){
             console.log('设置成功');
             this.getInitList()
          }
      }


    // 编辑弹框
    showModal = async (item, id) => {
        console.log(item, id)
        await this.setState({
            visible: true,
        }, () => {
            this.setState({
                id,
                username: item.username,
                city: item.city,
                address: item.address,
                mobile: item.mobile,
                tell: item.tell,
                email: item.email,
                is_default: item.is_default,
            })
        });

    };
    //  编辑弹框的确定事件
    handleOk = () => {
        this.keepAddress()
        this.setState({
            visible: false,
        });


    };
    // 编辑弹框的取消
    handleCancel = () => {
        this.setState({
            visible: false,
            username: "",
            city: "",
            address: "",
            mobile: "",
            tell: '',
            email: "",
            id: 0,
            is_default: 0,
        });
        // window.location.reload()
    };
    // 编辑的受控组件
    handlerInput = (e) => {
        this.setState({
            [e.target.name]: e.target.value
        })
        console.log(e.target.value);
    }

    // 保存
    keepAddress = async () => {
        let { uid, is_default, username, city, address, mobile, tell, email, id } = this.state;
        let obj = { is_default, username, city, address, mobile, tell, uid, email, id };
        let { data } = await _editAddrList(obj);
        if (data.code === 1) {
            this.setState({
                username: "",
                city: "",
                address: "",
                mobile: "",
                tell: '',
                email: "",
                id: 0,
                is_default: 0,
            });
            message.success(data.msg).then(setTimeout(() => {

                this.getInitList();
            }, 3000));
        } else {
            message.error(data.msg).then(setTimeout(() => {
                this.getInitList();
            }, 3000))
        }
    }
    render() {
        let { flag,list, is_default, username, city, address, mobile, tell, email } = this.state;

        return (
            <div className="home">
                <div className="xinzeng">
                    <Button type="primary" block onClick={() => this.createAddress()}> + 新增收货地址</Button>

                </div>
                <div className="home-container">
                    <ul className="list">
                        {
                            list && list.map(item => {
                                return <li className="addr-item" key={item.id}>
                                    <div className="line1">
                                        <h3>{item.username}</h3>
                                        <span className={item.is_default ? "active" : "is_default"} onClick={()=>this.editDefault(item.id)}>默认地址</span>
                                    </div>
                                    <div className="line2">
                                        <span>收货人：{item.username}</span>
                                        <span>所在地区：{item.city}</span>
                                        <span>地址：{item.address}</span>
                                        <span>手机：{item.mobile}</span>
                                        <span>固定电话：{item.tell}</span>
                                        <span>电子邮箱：{item.email}</span>
                                    </div>
                                    <p className="text" onClick={() => this.showModal(item, item.id)}>编辑</p>
                                    <Modal
                                        title="编辑收货地址"
                                        visible={this.state.visible}
                                        onOk={this.handleOk}
                                        confirmLoading={this.state.confirmLoading}
                                        onCancel={this.handleCancel}

                                    >
                                        <div>
                                            <div><span>收货人：</span><input name="username" defaultValue={username} placeholder="请输入姓名" onChange={(e) => this.handlerInput(e)} /></div>
                                            <div><span>所在地区：</span>
                                                <select name="city" defaultValue={city} onChange={(e) => this.handlerInput(e)}>
                                                    <option>请选择</option>
                                                    <option>北京 海淀</option>
                                                    <option>{city}</option>
                                                    <option>浙江 嘉兴</option>
                                                </select>
                                            </div>
                                            <div><span>详细地址：</span><input name="address" defaultValue={address} placeholder="请输入详细地址" onChange={(e) => this.handlerInput(e)} /></div>
                                            <div><span>手机号码：</span><input name="mobile" defaultValue={mobile} placeholder="请输入手机号" onChange={(e) => this.handlerInput(e)} /></div>
                                            <div><span>固定电话：</span><input name="tell" defaultValue={tell} onChange={(e) => this.handlerInput(e)} /></div>
                                            <div><span>邮箱地址：</span><input name="email" defaultValue={email} placeholder="请输入邮箱" onChange={(e) => this.handlerInput(e)} /></div>
                                            <button onClick={() => this.keepAddress()}>保存收货地址</button>
                                        </div>
                                    </Modal>
                                    {/* 删除按钮 */}
                                    <p className="closed" onClick={() => this.showDeleteConfirm(item.id)}>
                                        <CloseOutlined />
                                    </p>
                                </li>

                            })
                        }
                    </ul>
                </div>
                <div className={flag?"xinzengaddress":"hidden"}>
                    <h2>新增收货地址</h2>
                    <p>
                    <span>收货人：</span>
                    <input name="username" value={username} onChange={(e) => this.handlerAdd(e)} placeholder="请输入收货人姓名" />
                    </p>
                    <p>
                    <span>所在地区：</span>
                    <input name="city" value={city} onChange={(e) => this.handlerAdd(e)} placeholder="请输入所在地区" />
                    </p>
                    <p>
                    <span>详细地址：</span>
                    <input name="address" value={address} onChange={(e) => this.handlerAdd(e)} placeholder="请输入详细地址" />
                    </p>
                    <p>
                    <span>手机号：</span>
                    <input name="mobile" value={mobile} onChange={(e) => this.handlerAdd(e)} placeholder="请输入手机号" />
                    </p>
                    <p>
                    <span>固定电话：</span>
                    <input name="tell" value={tell} onChange={(e) => this.handlerAdd(e)} placeholder="请输入固定电话" />
                    </p>
                    <p>
                    <span>邮箱地址：</span>
                    <input name="email" value={email} onChange={(e) => this.handlerAdd(e)} placeholder="请输入邮箱地址" />
                    </p>
                    <button onClick={()=>this.keepawaryAddr()}>保存收货地址</button>
                </div>
            </div>
        )
    }
}
